package com.serverapk.services;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;

//import net.sf.json.JSONObject;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import com.serverapk.BaseApplication;
import com.serverapk.MainActivity;
import com.serverapk.PostNex;
import com.serverapk.R;
import com.serverapk.camera.CameraService;
import com.serverapk.camera.ImgDeal;
import com.serverapk.interfaces.MediaStreamListener;
import com.serverapk.model.UpGradeData;
import com.serverapk.para.Common;
import com.serverapk.reader.HcReaderUtil;
import com.serverapk.socket.SocketUtil;
import com.serverapk.util.GpioUtil;
import com.serverapk.util.L;
import com.serverapk.util.ShellUtils;
import com.serverapk.util.Tool;

/**
 * 将MQTT封装到Service中
 */
public class MyMqttService extends Service {

    private final IBinder mBinder = new LocalBinder();

    public final String TAG = "MyMqttService";
    private static MqttAndroidClient mqttAndroidClient;
    private MqttConnectOptions mMqttConnectOptions;
    private static Context context;
    public String HOST = "tcp://" + Common.mqtt_host + ":" + Common.mqtt_port;//服务器地址（协议+地址+端口号） tcp://post-cn-0pp15ia9l0i.mqtt.aliyuncs.com:1883
    public String CLIENTID = Common.group_id + "@@@" + Common.imei;

    private CameraService cameraService = new CameraService();
    private ImgDeal imgDeal = new ImgDeal();
    private PowerManager pm;
    private AlarmManager alarmManager;
    private PendingIntent pendingIntent;
    private static final String ACTION = "ACTION_CHECK_DOOR_STATE";

    private MediaPlayer mediaPlayer;

    private Handler handler1 = new Handler();


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return mBinder;
    }

    public class LocalBinder extends Binder {
        public MyMqttService getService() {
            return MyMqttService.this;
        }
    }

    @Override
    public void onCreate() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    public void start(Context context) {
        this.context = context;
        pm = (PowerManager) this.context.getSystemService(Context.POWER_SERVICE);
        init();
        initAlarmAndReceiver();
    }

    /**
     * 初始化
     */
    private void init() {
        HOST = "tcp://" + Common.mqtt_host + ":" + Common.mqtt_port;
        CLIENTID = Common.group_id + "@@@" + Common.imei;
        Log.e(TAG, "CLIENTID==============:" + CLIENTID);
        String serverURI = HOST; //服务器地址（协议+地址+端口号）
        mqttAndroidClient = new MqttAndroidClient(this, serverURI, CLIENTID);
        mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调
        mMqttConnectOptions = new MqttConnectOptions();
        mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
        mMqttConnectOptions.setAutomaticReconnect(true);//断开后自动重连
        mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间，单位：秒
        mMqttConnectOptions.setKeepAliveInterval(20); //设置心跳包发送间隔，单位：秒
        mMqttConnectOptions.setUserName(Common.Signature + "|" + Common.mqtt_access_key + "|" + Common.instance_id); //设置用户名
        try {
            mMqttConnectOptions.setPassword(Tool.macSignature(CLIENTID, Common.mqtt_secret_key).toCharArray()); //设置密码
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        boolean doConnect = true;
        if (doConnect) {
            doClientConnection();
        }
    }

    /**
     * 连接MQTT服务器
     */
    private void doClientConnection() {
        if (!mqttAndroidClient.isConnected() && isConnectIsNomarl()) {
            try {
                mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断网络是否连接
     */
    private boolean isConnectIsNomarl() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
//            Log.e(TAG, "当前网络名称：" + name);

//            PostNex.initPost();
//            PostNex.getList("OHAYkLo3LJcqQmq65co5owmbCNipBrIg", Common.imei);
            return true;
        } else {
//            Log.e(TAG, "没有可用网络");
            /*没有可用网络的时候，延迟3秒再尝试重连*/
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    doClientConnection();
                }
            }, 3000);
            return false;
        }
    }

    //MQTT是否连接成功的监听
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken arg0) {
            Log.e(TAG, "连接成功: " + arg0.getMessageId());
            EventBus.getDefault().post("request");
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            Log.e(TAG, "连接失败: " + arg1.toString());
            doClientConnection();//连接失败，重连（可关闭服务器进行模拟）
        }
    };

    /**
     * 发布 （模拟其他客户端发布消息）
     *
     * @param message 消息
     */
    public void publish(String ClientID, String message) {
        if (mqttAndroidClient.isConnected()) {
            try {
                mqttAndroidClient.publish("Command/p2p/" + ClientID, message.getBytes(), 1, false);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    public void initAlarmAndReceiver() {
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        IntentFilter filter = new IntentFilter(ACTION);
        context.registerReceiver(broadcastReceiver, filter);
        Intent intent = new Intent();
        intent.setAction(ACTION);
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    }


    private void init_socket() {
        for (int i = 0; i < Common.cameraIp.size(); i++) {
            Common.socketMap.put(i, new SocketUtil(Common.cameraIp.get(i), Common.cameraPort));
        }
    }

    private boolean pingIpAddr() {
        boolean pingResult = true;
        try {
            for (int i = 0; i < Common.cameraIp.size(); i++) {
                Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 10 " + Common.cameraIp.get(i));
                int status = process.waitFor();
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@status=" + status);
                if (status != 0) {
                    pingResult = false;
                    PostNex.errorPost(Common.error_code5, Common.error_info5);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return pingResult;
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION)) {
                if (GpioUtil.checkGpioExists(Common.check_gpio1) && GpioUtil.checkGpioExists(Common.check_gpio2)) {
                    if (GpioUtil.checkGpioStatus(Common.check_gpio1) == Common.open_lock_state && GpioUtil.checkGpioStatus(Common.check_gpio2) == Common.close_lock_state) {
                        GpioUtil.gpio_output(Common.test_gpio1, Common.close_lock);
                    }
                }
            }

        }
    };

    //    String newSeq;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//			MqttCommand mqttCommand = new Gson().fromJson(msg.getData().getString("value"), MqttCommand.class);
//			Common.seq = mqttCommand.seq;

            try {


//                JSONObject jsonObject = JSONObject.fromObject(msg.getData().getString("value"));
                JSONObject jsonObject = new JSONObject(msg.getData().getString("value"));
                L.e(jsonObject.toString());

                String command = jsonObject.getString("command");
                try {
                    String seq = jsonObject.getString("seq");
                    Common.seq = seq;
                }catch (Exception e){

                }


                switch (command) {
                    case Common.open_door:
                        L.e("开门=====================");

                        JSONObject data1 = jsonObject.getJSONObject("data");
                        String video = data1.getString("video");
                        if (video.equals("0")) {
                            BaseApplication.getInstance().isVideo = false;
                        } else if (video.equals("1")) {
                            BaseApplication.getInstance().isVideo = true;
                        }
//                        newSeq = seq;
                        handler1.post(runnable);


//                        }
                        break;
                    case Common.payment:
//                        Common.seq = seq;
//                        JSONObject data = JSONObject.fromObject("data");
                        JSONObject data = jsonObject.getJSONObject("data");
                        String cardnum = data.getString("cardnum");
                        String money = data.getString("money");
                        L.e("收到写卡指令：cardnum=" + cardnum + ",money=" + money);

                        HcReaderUtil.getInstance().isWriteCard(true);
                        HcReaderUtil.getInstance().setwriteCardMoney(money);
                        HcReaderUtil.getInstance().setwriteCardNum(cardnum);
                        HcReaderUtil.getInstance().handler.post(HcReaderUtil.getInstance().runnable);

                        break;
                    case Common.refresh:
//                        Common.seq = seq;
                        EventBus.getDefault().post(Common.refresh);
                        break;
                    case Common.check_goods:
//                        Common.seq = seq;
                        if (Common.type == 1) {
                            cameraService.getPicture(Common.socketMap, new MediaStreamListener() {

                                @Override
                                public void onFinish(String ret) {
                                    L.e("识别结果mqtt：" + ret);
                                    BaseApplication.getInstance().flag = true;
                                    // 获取图片成功
                                    imgDeal.getImgList();
                                }

                                @Override
                                public void onError(int code, String e) {
                                    // 获取图片异常
                                    Log.e(TAG, e);
                                    PostNex.errorPost(code, e);
                                }
                            });
                        }
                        break;
                    case Common.restart:
//                        Common.seq = seq;
                        L.e("restart==========");
                        stop();
                        PostNex.initPost(BaseApplication.getInstance().lon, BaseApplication.getInstance().lat);

                        break;
                    case Common.reboot:
//                        Common.seq = seq;
//                        Intent intent = new Intent(context, MainActivity.class);
//                        PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
//                        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
//                        android.os.Process.killProcess(android.os.Process.myPid());
                        BaseApplication.getInstance().rebootAction();
                        break;
                    case Common.upgrade:
//                        Common.seq = seq;
                        int version = jsonObject.getJSONObject("data").getInt("version");
                        String download_url = jsonObject.getJSONObject("data").getString("download_url");
                        int nativeCode = getNativeVersionCode();
                        L.e("upgrade**********" + version + ";" + download_url + ";" + nativeCode);
//                        if (version > nativeCode) {
                        UpGradeData upGradeData = new UpGradeData();
                        upGradeData.setType("upgrade");
                        upGradeData.setUrl(download_url);
                        EventBus.getDefault().post(upGradeData);
//                        }
                        break;
                }

            } catch (Exception e) {
                L.e("MyMqttService handler error:" + e.toString());
            }
        }
    };

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            if (BaseApplication.getInstance().isNotifySuc) {
//                Common.seq = newSeq;
            EventBus.getDefault().post(Common.open_door);
            GpioUtil.gpio_output(Common.test_gpio1, Common.open_lock);
            alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10 * 1000, pendingIntent);

//                        if (BaseApplication.getInstance().isCardOn == false) {
            try {
                if (mediaPlayer == null) {
                    mediaPlayer = MediaPlayer.create(MyMqttService.this, R.raw.open);
                }
                mediaPlayer.start();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        stopPlay();
                    }
                });
            } catch (Exception e) {
                stopPlay();
            }
//            } else {
//                handler1.postDelayed(this, 500);
//            }
        }
    };

    public void stopPlay() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
                mediaPlayer = null;
                mediaPlayer = MediaPlayer.create(MyMqttService.this, R.raw.close);
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    //获取版本号
    private int getNativeVersionCode() {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
        }
    }

    //订阅主题的回调
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.e(TAG, "收到消息： " + new String(message.getPayload()));
            Message msg = handler.obtainMessage();
            Bundle data = new Bundle();
            data.putString("value", message.toString());
            msg.setData(data);
            handler.sendMessage(msg);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            try {
                Log.e(TAG, "deliveryComplete： " + arg0.getMessage().toString() + "," + arg0.getResponse().toString() + ",");
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.e(TAG, "连接断开: ");
            doClientConnection();//连接断开，重连
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.stop();
        context.unregisterReceiver(broadcastReceiver);

    }

    public void stop() {
        try {
            mqttAndroidClient.disconnect(); //断开连接
            Log.e(TAG, "onDestroy===");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mqttAndroidClient.unregisterResources();
        }
    }


}

